package com.dinim.math;

import com.dinim.matrix.twodimensional.IPoint2D;
import com.dinim.object.Point2D;

public class GeometryUtil {

    public static final double getCrossProduct(IPoint2D p0, IPoint2D p1, IPoint2D p2){
        double x0 = p0.getX();
        double y0 = p0.getY();
        double x1 = p1.getX();
        double y1 = p1.getY();
        double x2 = p2.getX();
        double y2 = p2.getY();
        double crossproduct = (x1 - x0) * (y2 - y1) - (y1 - y0) * (x2 - x1);
        return crossproduct;
    }
    
    public static final double getGradient(double x1, double y1, double x2, double y2){
//        Double d = new Double(((y2-y1)/(x2-x1)));
//        if(d.isNaN()){
//            System.out.println("nananananan");
//        }
        if((x1 == x2) && (y1 == y2)){
            return 0;
        }
        return ((y2-y1)/(x2-x1));
    }
    
	public static final double getLength(double x1, double y1, double x2, double y2){
        double length = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
		if(length < 0){
		    throw new RuntimeException();
        }
        return length;
	}

    public static final IPoint2D getIntersection(IPoint2D beg1, IPoint2D end1, IPoint2D beg2, IPoint2D end2){

        double x1 = beg1.getX();
        double x2 = end1.getX();
        double x3 = beg2.getX();
        double x4 = end2.getX();
        
        double y1 = beg1.getY();
        double y2 = end1.getY();
        double y3 = beg2.getY();
        double y4 = end2.getY();

        double ua = ((((x4-x3)*(y1-y3))-((y4-y3)*(x1-x3))) / (((y4-y3)*(x2-x1))-((x4-x3)*(y2-y1))));
        double ub = ((((x2-x1)*(y1-y3))-((y2-y1)*(x1-x3))) / (((y4-y3)*(x2-x1))-((x4-x3)*(y2-y1))));

        /*
         * ua and ub must lie between 0 and 1 so the intersectionpoint lies on both lines
         */
        if((ua<0) || (ua>1) || (ub<0) || (ub>1)){
            return null;
        }
        
        double x = x1 + ua * (x2 - x1);
        double y = y1 + ua * (y2 - y1);

        /*
         * in case of parallel lines, the denomitators for the equations ua and ub will be 0,
         * which will cause the equations to give back an infinite value
         */
        if (Double.valueOf(x).isInfinite() || Double.valueOf(y).isInfinite() ||
            Double.valueOf(x).isNaN() || Double.valueOf(y).isNaN()) {
            return null;
        } else {
            return new Point2D(x, y);
        }
    }
    
}
